<?php

namespace App\Http\Services;

/*用户service层*/

use App\Http\Model\AudioApi;
use App\Http\Model\Config;
use App\Http\Model\Dish;
use App\Http\Model\Gift;
use App\Http\Model\Room;
use App\Http\Model\User;
use Illuminate\Auth\DatabaseUserProvider;
use Illuminate\Support\Facades\Redis;

class RoomServices extends CommonServices
{
    private $audio_model;
    private $dish_model;
    private $gift_model;
    private $level_minute = ['60', '180', '300']; // 等级对应时间
    const send_room_msg = ['我是欧皇 我为王', '老板，再来10000场', '我要拿大奖', '我相信，我可以', '给主持献上666', '主持你最美，但是奖励更美', '大奖对于我来说都是小问题', '不就是抽奖嘛，放着我来'];//房间内文案
    const pay_diamond = ['200', '1500', '5000', '20000'];//扣除钻石
    const mall_list_ids = [231, 200, 199];//座驾id


    public function __construct()
    {

        $this->audio_model = new AudioApi();
        $this->dish_model = new Dish();
        $this->gift_model = new Gift();
    }

    //开启付费打碟
    public function payDishRoom($room_id, $minute, $level, $pay_user_id)
    {

        $key = 'CLICK:OPEN:DISH';
        redis_lock($key);
        $gift_id = 332;
        $status = [
            'code' => '0',
            'msg' => '发起成功',
            'room_id' => $room_id,
            'user_id' => $pay_user_id
        ];

        do {
            //扣除用户费用
            $pay_diamond = self::pay_diamond;
            $pay_diamond = $pay_diamond[$level];

            //付费打碟中
            $pay_cache = $this->dish_model->getPayDishCache($room_id);
            if (time() > $pay_cache && $pay_cache) {
                $status['code'] = 3002;
                $status['msg'] = '未结算奖励，请稍后~';
                break;
            }
            if ($pay_cache) {
                $status['code'] = 3001;
                $status['msg'] = '该房间已存在付费打碟活动';
                break;
            }
            //免费打碟中
            $free_cache = $this->dish_model->getFreeRoomIdCache($room_id);
            if ($free_cache !== null) {
                $status['code'] = 3001;
                $status['msg'] = '该房间正在参与免费打碟活动,请稍后重试';
                break;
            }

            $recharge = $this->audio_model->diamond_recharge($pay_user_id, $pay_diamond, 3);
            if ($recharge['code'] != 0) {
                $status['code'] = 3005;
                $status['msg'] = '扣费失败,请稍后重试';
                break;
            }
            $time = $minute * 60;
            $this->dish_model->addPayDishCache($room_id, $time, $level);
            $this->dish_model->createPayRoomIdCache($room_id, $time);
            $this->dish_model->incrPayDiamond(0, $pay_diamond, $room_id, $pay_user_id);//开启记录缓存
            $award_gift_num = $pay_diamond / 100;
            if ($award_gift_num != 2) {
                //赠送音浪
                $res = $this->audio_model->sendGift($pay_user_id, $gift_id, 15, $award_gift_num);
                if ($res) {
                    //支出礼物缓存
                    $this->dish_model->userGetGiftNum(0, $gift_id, $award_gift_num);
                    $status['msg'] = '您已成功创建打碟活动,' . $award_gift_num . '个音浪已返还到您背包内，请注意查收';
                    $msg = '您已成功创建打碟活动,音浪已返还到您背包内,请注意查收~';
                    $this->audio_model->sendMsgApi($pay_user_id, $msg);
                }
            }

            if ($pay_diamond == 20000) {
                $room_model = new  Room();
                $room_cache = $room_model->getRoomInfoToRoomIdCache($room_id);
                $room_cache = json_decode($room_cache, true);
                $text = $room_cache['room_uid'] . '厅成功创建打碟游戏,超值大奖等你来拿,————去看看';
                $this->audio_model->sendAllAppApi($pay_user_id, $room_id, $text);
            }
            $this->audio_model->sendRoomDishMsg(['room_id' => $room_id, 'user_id' => $pay_user_id, 'text' => '主持开启了打碟活动，快来参与吧！']);


        } while (false);
        //唤起api消息
        $this->audio_model->sendDishMsg($status);
        redis_unlock($key);
    }


    /*
     * 获取当前开启房间
     * 可免费打碟条件：1整点时开启 2 整点没有付费打碟
     *
     * */
    public function getOpenRoom()
    {
        $status = [
            'code' => '200',
            'msg' => '参与成功',
            'room_id' => 0
        ];
        $h = date('H');
        if (in_array($h, [3, 4, 5, 6, 7, 8, 9])) {
            write_log('openRoom', '休息时间', []);//开启房间
            return false;
        }
        //获取次数
        $num = $this->dish_model->getAwardAllNum();
        if ($num != null) {
            return false;
        }
        $res = $this->audio_model->getOpenRoomId();
        if ($res['code'] != 0) {
            return false;
        }

        $room_ids = $res['data']['list'];
        write_log('openRoom', '房间开启', $room_ids);//开启房间
        //循环发送免费打碟消息
        $room = [];
        foreach ($room_ids as $k => $v) {
            //已开启免费跳出
            $free_dish = $this->dish_model->getFreeRoomIdCache($v);
            if ($free_dish) {
                continue;
            }
            //查看是否开启付费打碟
            $pay_status = $this->dish_model->getPayDishCache($v);
            if ($pay_status != null) {
                continue;
            }
            $this->dish_model->createFreeRoomIdCache($v);
            //开启免费打碟
            $status['room_id'] = $v;
            $this->audio_model->sendDishMsg($status);
            $room[] = $v;
        }
        if ($room) {
            $this->dish_model->startFreeDish();
            $this->dish_model->setAwardAllNum();
            //设置可点击剩余时间
            $this->dish_model->setCheckClickTime();
        }

    }


    /*
     * 关闭房间免费打碟
     * @param $room_id 新开启房间id
     * */
    public function closeFreeDish($room_id)
    {
        $this->dish_model->delFreeDishInfo($room_id);
    }


    /*
     * 用户参与打碟
     * @param $room_id  房间id
     * @param $user_id  参与用户id
     * @param $type  0免费 1付费
     * @param $level  付费钻石数量
     * */
    public function clickDishAward($room_id, $user_id, $type, $level)
    {
        $status = [
            'code' => '200',
            'msg' => '参与成功',
            'data' => []
        ];

        switch ($type) {
            case 0://免费
                //查询房间是否有免费
                $free_room = $this->dish_model->getFreeDish();
                if (empty($free_room)) {
                    $status = [
                        'code' => '3001',
                        'msg' => '免费领取暂未开启',
                        'data' => []
                    ];
                    break;
                }
                //查看用户是否已经参与
                $user_join_dish = $this->dish_model->getFreeDishUserToRoom($room_id, $user_id);
                if ($user_join_dish) {
                    //已经参与
                    $status = [
                        'code' => '3003',
                        'msg' => '您已参与~请等待奖励发放',
                        'data' => []
                    ];
                    break;
                }
                //判断时间是否可以参与
                $getCheckTime = $this->dish_model->getClickTime();
                if ($getCheckTime <= 20 && $getCheckTime >= 0) {
                    //休息时间
                    $status = [
                        'code' => '3004',
                        'msg' => '奖励发放中~请休息' . $getCheckTime . 's后重试',
                        'data' => []
                    ];
                    break;
                }
                $count_num = $this->dish_model->getAwardAllNum();
                if ($count_num > 5) {
                    $status = [
                        'code' => '3002',
                        'msg' => '奖励已经发放完啦~请下次领取',
                        'data' => []
                    ];
                    break;
                }
                //参与房间打碟
                $this->dish_model->addFreeDishRoomToUser($room_id, $user_id);
                break;
            default://参与付费打碟
                //查看房间是否有付费打碟
                $pay_room = $this->dish_model->getPayDishCache($room_id);
                if (empty($pay_room) || time() > $pay_room) {
                    $status = [
                        'code' => '3005',
                        'msg' => '未开启打碟爆奖',
                        'data' => []
                    ];
                    break;
                }
                //扣除用户钻石
                $pay_diamond = ['50', '150', '270', '500'];
                $user_pay_diamond = $pay_diamond[$level];
                $decr = $this->audio_model->diamond_recharge($user_id, $user_pay_diamond, 2);

                if ($decr['code'] != 0) {
                    $status = [
                        'code' => $decr['code'],
                        'msg' => $decr['msg'],
                        'data' => []
                    ];
                    break;
                }

                //参与房间打碟
                $this->dish_model->addPayDishRoomToUser($room_id, $user_id);
                $this->dish_model->incrPayDiamond(1, $user_pay_diamond);//收入
                $text = self::send_room_msg;
                $this->audio_model->sendRoomDishMsg(['room_id' => $room_id, 'user_id' => $user_id, 'text' => $text[rand(0, 7)]]);
                break;
        }
        return $status;
    }

    //免费奖励发放
    public function freeAwardGift()
    {
        $h = date('H');
        $i = date('i');
        if ($i > 7 || in_array($h, [3, 4, 5, 6, 7, 8, 9])) {
            write_log('freeAwardGift', '免费礼物发放休息时间', []);//开启房间
            return false;
        }

        $level = 0;
        //获取发放总次数
        $award_all_num = $this->dish_model->getAwardAllNum();
        if ($award_all_num > 4) {
            return false;//num上限
        }
        //缓冲时间
        $check_time = $this->dish_model->getClickTime();
        if ($check_time > 20) {
            return false;//不是休息时间
        }

        //查看发放状态
        $award_status = $this->dish_model->getFreeStatus();
        if ($award_status != null) {
            //不可发放
            return false;//不可发放状态 或已经发放过
        }

        //休息时间 且可以发放
        do {
            //获取所有免费房间
            $room_ids = $this->dish_model->getFreeRoomIdCache();
            if (!$room_ids) {
                break;
            }
            if ($check_time < 0) {
                $this->dish_model->setCheckClickTime(20);
            }
            //更新休息时间
            foreach ($room_ids as $k => $v) {
                //判断发放次数
                if ($v >= 5) {
                    $this->dish_model->delFreeDishInfo($k);
                    continue;
                }
                //修改免费发放次数
                $this->dish_model->updateFreeRoomAwardNum($k);
                $join_user_ids = $this->dish_model->getFreeDishALLUserToRoom($k);
                $join_user_ids = array_keys($join_user_ids);
                $count = count($join_user_ids);
                if (empty($join_user_ids)) continue;
                foreach ($join_user_ids as $vv) {
                    //发放奖励用户入队列
                    $data['user_id'][] = $vv;
                    $this->dish_model->pushFreeAwardPondToUser($vv, $k);
                    //删除用户参与记录
                    $this->dish_model->delFreeDishUser($k, $vv);
                }
                $this->dish_model->popFreeAwardPondToUser($k, $count);
            }
            //发放完成，获取剩余休息时间
            $ttl = $this->dish_model->getClickTime();
            if ($ttl <= 0) {
                $ttl = 1;//超时发放休息时间默认1s
            }
            //保证休息时间为剩余休息时间
            $this->dish_model->setCheckClickTime($ttl);
            $this->dish_model->getClickTime();
            //更新上次发放时间
            $this->dish_model->updateFreeDishAwardTime($ttl + time());
            if ($ttl > 0) {
                //剩余缓冲时间 + 60 = 下次发放时间   时间到则可发放状态消失
                $this->dish_model->updateFreeStatus(1, $ttl + 60);
            }

            //发放总次数加1
            $this->dish_model->updateAwardAllNum();

        } while (false);
        return true;
    }


    /*
     * 付费奖励发放
     * */
    public function awardPayGift()
    {
        //获取所有付费房间
        $room_ids = $this->dish_model->getPayRoomIdCache();
        do {
            if (!$room_ids) {
                return false;
            }
            foreach ($room_ids as $k => $v) {
                $count = 0;
                //查看房间打碟等级
                $time_level = $this->dish_model->getPayDish($k);
                $level = $time_level[$k];
                //查看所有参与用户
                $join_user_ids = $this->dish_model->getPayDishUserId($k);
                //删除付费房间待开奖池子
                $this->dish_model->delPayRoomIdCache($k);
//                //删除房间信息
                $this->dish_model->delPayDishLevel($k);
                if (!$join_user_ids) continue;
                foreach ($join_user_ids as $kk => $vv) {
                    $count = $count + $vv;
                    $this->dish_model->pushPayAwardPondToUser($kk, $vv, $k);
                    $this->dish_model->delPayDishRoomToUser($k, $kk);//删除用户参与付费房间记录
                }

                //队列处理礼物发放
                $this->dish_model->popPayAwardPondToUser($k, $count, $level);
            }
        } while (false);
    }


    //获取用户所在房间打碟相关信息
    public function getUserDishInfo($room_id, $user_id)
    {
        //查看房间当前开启的打碟是免费&付费
        $status = [
            'code' => '200',
            'msg' => '成功',
            'data' => [
                'diamond' => 0,// 钻石余额
                'type' => 2,// 0免费 1付费 2为没有开启打碟
                'timeout' => [0, 0, 0],// 剩余开奖时间
                'click' => 0,// 连击次数
                'level' => 0,//0免费 1 200钻 2 1500钻 3 5000钻 4 20000钻
                'message' => '点击参与',// 连击次数
            ]
        ];
        $time = '000';

        do {
            $free_room = $this->dish_model->getFreeRoomIdCache($room_id);
            $pay_room = $this->dish_model->getPayDish($room_id);
            if ($free_room !== null) {
                $timestamp = $this->dish_model->getFreeDish();
                $award_num = $this->dish_model->getAwardAllNum();
                $desc_time = time() - $timestamp;
                if ($desc_time < 0) {
                    $time = '000';
                } else {
                    $time = 60 - time() + $timestamp;
                }
                $status['data']['type'] = 0;
                $status['data']['click'] = 1;
                $status['data']['message'] = '参与免费打碟';
            } else if ($pay_room) {
                $timestamp = $this->dish_model->getPayRoomId($room_id);
                if (!$timestamp) {
                    break;
                }
                $time = $timestamp - time() < 0 ? '000' : $timestamp - time();
                $status['data']['type'] = 1;
                $status['data']['level'] = $pay_room[$room_id];
                //查看点击次数
                $status['data']['click'] = $this->dish_model->getPayDishUserId($room_id, $user_id) ?? 0;
                $status['data']['message'] = '连击爆奖';
            } else {
                $status['data']['type'] = 2;
            }

            $status['data']['timeout'] = str_split($time, 1);
            $status['data']['second'] = $time;

        } while (false);
        //获取用户钻石数量
        $user_model = new  User();
        $user_info = $user_model->getUserFinance($user_id);
        $money = $user_info['diamond_balance'] ?? 0;
        if ($money >= 10000) {
            $money = sprintf("%.2f", $money / 10000) . 'k';
        }
        $status['data']['diamond'] = $money;
        return $status;
    }


    /*
     * 获取用户中奖记录
     * */
    public function getUserGiftLog($user_id)
    {
        $log = $this->dish_model->getAwardLog($user_id);
        $data = [];
        $i = 0;
        $log = array_reverse($log);
        foreach ($log as $k => $v) {
            $key = explode('/', $k);
            if (in_array($key[0], self::mall_list_ids)) {
                $gift = json_decode($this->gift_model->getMallInfoCache($key[0]), true);
                $data[$i]['msg'] = $gift['goods_name'] . 'x' . $v;
                $data[$i]['type'] = '已存入装扮';
            } else {
                $gift = json_decode($this->gift_model->getGiftInfoCache($key[0]), true);
                $data[$i]['msg'] = $gift['name'] . 'x' . $v;
                $data[$i]['type'] = '已存入背包';
            }
            $data[$i]['date'] = $key[1];
            $i++;
        }
        return $data;
    }

    public function jumpDishRoom()
    {
        $time = time() + 6000;
        $room_ids = $this->dish_model->getPayRoomIdCache($time);
        $room_ids = array_keys($room_ids);
        if ($room_ids) {
            $key = rand(0, count($room_ids) - 1);
        } else {
            $res = $this->audio_model->getOpenRoomId();
            $room_ids = $res['data']['list'];
            $key = rand(0, count($room_ids) - 1);
        }
        $room_id = $room_ids[$key];
        return ['room_id' => $room_id];
    }

    public function createAwardPond($level = 0)
    {
        $this->dish_model->createAwardPond($level);
    }

    public function popAwardPond($level = 0, $len, $type)
    {
        $this->dish_model->popAward($level, $len, $type);
    }
}
